<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-header">放假日期</div>
                <div class="layui-card-body">
                    <div class="layui-upload">
                        <button id="addHoliday" type="button" class="layui-btn layui-btn-normal"><i class="layui-icon layui-icon-add-1"></i>添加</button>
                        <div class="layui-upload-list">
                            <table class="layui-table" frame="void">
                                <thead><tr>
                                    <th>日期</th>
                                    <th>操作</th>
                                </tr></thead>
                                <tbody id="holidayTbody"></tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-card">
                <div class="layui-card-header">替换日期</div>
                <div class="layui-card-body">
                    <div class="layui-upload">
                        <button id="addReplaceDate" type="button" class="layui-btn layui-btn-normal"><i class="layui-icon layui-icon-add-1"></i>添加</button>
                        <div class="layui-upload-list">
                            <table class="layui-table" frame="void">
                                <thead><tr>
                                    <th>旧日期</th>
                                    <th>新日期</th>
                                    <th>操作</th>
                                </tr></thead>
                                <tbody id="replaceDateTbody"></tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    Date.prototype.Format = function (fmt) { //author: meizz
        var o = {
            "M+": this.getMonth() + 1, //月份
            "d+": this.getDate(), //日
            "h+": this.getHours(), //小时
            "m+": this.getMinutes(), //分
            "s+": this.getSeconds(), //秒
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度
            "S": this.getMilliseconds() //毫秒
        };
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    };

    layui.use(['form','laydate'], function () {
        var element = layui.element, view = layui.view,
            admin = layui.admin, $ = layui.$, laydate = layui.laydate;

        let holidayConfigUrl = "/admin/config/lesson/holiday";
        let replaceConfigUrl = "/admin/config/lesson/replace";

        function renderTable() {
            $.ajax({
                url:        "/admin/config",
                dataType:   'json',
                type:       'GET',
                complete    :function (result) {
                    let data = result.responseJSON;
                    let status = data.status;
                    if (status !== 200){
                        layer.msg("请求配置数据失败！");
                        return;
                    }
                    data = data.data;
                    let lessonConf = data['lessonConfig'];
                    let holidayDate = lessonConf['dateHolidaySet'];
                    let replaceDate = lessonConf['dateReplaceMap'];
                    renderHolidayTable(holidayDate);
                    renderReplaceDateTable(replaceDate);
                }
            });
        }


        function renderHolidayTable(holidayDateArray) {
            $('#holidayTbody').empty();
            holidayDateArray.forEach(function (item) {
                let tr = $([
                    '<tr>'
                    ,'<td>' + item +  '</td>'
                    ,'<td><button name=\'del-hol-' + item + '\' class="layui-btn layui-btn-xs layui-btn-danger"><i class="layui-icon layui-icon-delete"></i></button></td>'
                    ,'</tr>'
                ].join(''));
                tr.find('.layui-btn-danger').on('click', function () {
                    let date = this.name.substring(8);
                    delHoliday(date);
                });
                $('#holidayTbody').append(tr);
            });
        }

        function renderReplaceDateTable(replaceDateMap) {
            $('#replaceDateTbody').empty();
            for (let oldDate in replaceDateMap) {
                let tr = $([
                    '<tr>'
                    , '<td>' + oldDate + '</td>'
                    , '<td>' + replaceDateMap[oldDate] + '</td>'
                    , '<td><button name=\'del-rep-' + oldDate + '\' class="layui-btn layui-btn-xs layui-btn-danger"><i class="layui-icon layui-icon-delete"></i> </button></td>'
                    ,'</tr>'
                ].join(''));
                tr.find('.layui-btn-danger').on('click', function () {
                    let oldDate = this.name.substring(8);
                    delReplaceDate(oldDate);
                });
                $('#replaceDateTbody').append(tr);
            }
        }

        /**
         * 监听创建放假时间
         */
        $('#addHoliday').click(function (event) {
            let now = new Date().Format('yyyy-MM-dd');
            layer.open({
                title: '朕要放假'
                ,content: '<input type="text" id="holidayDate" name="holidayDate" class="layui-input">'
                ,success: function(index, layero){
                    laydate.render({
                        elem: '#holidayDate'
                        ,value: now
                    });
                }
                ,yes: function(index, layero){
                    let date = $('#holidayDate').val();
                    addHolidayDate(date);
                    layer.close(index);
                }
            });
        });


        /**
         * 添加放假时间
         */
        function addHolidayDate(date) {
            let load = layer.load(2);
            let data = {
                'date': date
            };
            $.ajax({
                url:        holidayConfigUrl,
                dataType:   'json',
                type:       'POST',
                data:       data,
                complete    :function (result) {
                    layer.close(load);
                    result = result.responseJSON;
                    let status = result['status'];
                    if (status !== 200) {
                        layer.msg(result['message']);
                    }else {
                        layer.msg("添加成功");
                    }
                    renderTable();
                }
            })
        }

        /**
         * 删除放假日期
         */
        function delHoliday(date) {
            layer.open({
                title: '不放假了'
                ,content: '确认删除 ' + date
                ,yes: function(index, layero){
                    let load = layer.load(2);
                    let data = {'date': date};
                    $.ajax({
                        url:            holidayConfigUrl,
                        dataType:       'json',
                        type:           'DELETE',
                        data:           data,
                        complete:       function (result) {
                            layer.close(load);
                            result = result.responseJSON;
                            let status = result['status'];
                            if (status !== 200) {
                                layer.msg(result['message']);
                            }else {
                                layer.msg('删除成功');
                                renderTable();
                            }
                        }
                    })
                }
            });
        }


        /**
         * 监听创建放假时间
         */
        $('#addReplaceDate').click(function (event) {
            let now = new Date().Format('yyyy-MM-dd');
            layer.open({
                title: '替换日期'
                ,content: '旧日期：<input type="text" id="oldDate" name="holidayDate" class="layui-input"><br>' +
                    '新日期：<input type="text" id="newDate" name="holidayDate" class="layui-input">'
                ,success: function(index, layero){
                    laydate.render({
                        elem: '#oldDate'
                        ,value: now
                    });
                    laydate.render({
                        elem: '#newDate'
                        ,value: now
                    })
                }
                ,yes: function(index, layero){
                    let oldDate = $('#oldDate').val();
                    let newDate = $('#newDate').val();
                    addReplaceDate(oldDate, newDate);
                }
            });
        });

        /**
         * 添加替换日期
         */
        function addReplaceDate(oldDate, newDate) {
            let load = layer.load(2);
            let data = {
                'oldDate': oldDate,
                'newDate': newDate
            };
            $.ajax({
                url:            replaceConfigUrl,
                dataType:       'json',
                type:           'POST',
                data:           data,
                complete:       function (result) {
                    layer.close(load);
                    result = result.responseJSON;
                    let status = result['status'];
                    if (status !== 200) {
                        layer.msg(result['message']);
                    }else {
                        layer.msg("添加成功");
                        renderTable();
                    }
                }
            })
        }

        /**
         * 删除替换日期
         */
        function delReplaceDate(oldDate) {
            layer.open({
                title: '不替换了'
                ,content: '确认删除 ' + oldDate
                ,yes: function(index, layero){
                    let load = layer.load(2);
                    let data = {'oldDate': oldDate};
                    $.ajax({
                        url:            replaceConfigUrl,
                        dataType:       'json',
                        type:           'DELETE',
                        data:           data,
                        complete:       function (result) {
                            layer.close(load);
                            result = result.responseJSON;
                            let status = result['status'];
                            if (status !== 200) {
                                layer.msg(result['message']);
                            }else {
                                layer.msg('删除成功');
                                renderTable();
                            }
                        }
                    })
                }
            });
        }

        renderTable();
    });
</script>
